package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.RSAUtils;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.QuJiHuaUtil;
import com.block.datapush.service.apipush.utils.XinYongPaiUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 信用派  双授权
 */
@Service
public class QuJiHuaApiBService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;
    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("userPhone", memberSourceInfo.getMobileMd5());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("ipAddress", memberSourceInfo.getReqIp());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("idCard", memberSourceInfo.getIdcard());
        bizMap.put("sex", memberSourceInfo.getSex()==1?1:0);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("monthlyIncome", QuJiHuaUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("loanAmount", QuJiHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTerm", QuJiHuaUtil.getLoanTerm(memberSourceInfo.getLoanAmount()));
        bizMap.put("qualification", QuJiHuaUtil.getXueLi(memberSourceInfo.getXueli()));
        bizMap.put("profession", QuJiHuaUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("gjj", QuJiHuaUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialInsurance", QuJiHuaUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("house", QuJiHuaUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", QuJiHuaUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("sesame", QuJiHuaUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("insurancePolicy", QuJiHuaUtil.getbaoxian(memberSourceInfo.getBaoxian()));


        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("data", encrypt);

        log.info("【趣记花半流程固价】撞库开始【queryUrl】{}【bizMap】{}【headerMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(headerMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(headerMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【趣记花半流程固价】撞库结束【result】{}", resultObject);

        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code+"");
        pushApiResult.setMessage(message);
        pushApiResult.setResultInfo(result);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));

        if(StrUtil.equals(String.valueOf(code),"0")){
            pushApiResult.setPushSuccess(true);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            extJson.put("outOrderNo", memberSourceInfo.getMobileMd5());
        }


        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getRegisterUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("userPhone", memberSourceInfo.getMobile());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("ipAddress", memberSourceInfo.getReqIp());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("idCard", memberSourceInfo.getIdcard());
        bizMap.put("sex", memberSourceInfo.getSex()==1?1:0);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("monthlyIncome", QuJiHuaUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("loanAmount", QuJiHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTerm", QuJiHuaUtil.getLoanTerm(memberSourceInfo.getLoanAmount()));
        bizMap.put("qualification", QuJiHuaUtil.getXueLi(memberSourceInfo.getXueli()));
        bizMap.put("profession", QuJiHuaUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("gjj", QuJiHuaUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialInsurance", QuJiHuaUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("house", QuJiHuaUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", QuJiHuaUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("sesame", QuJiHuaUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("insurancePolicy", QuJiHuaUtil.getbaoxian(memberSourceInfo.getBaoxian()));

        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("data", encrypt);

        log.info("【趣记花半流程固价】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(headerMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(headerMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【趣记花半流程固价】导单结束【result】{}", resultObject);
        String code = resultObject.getString("code");
        String url = resultObject.getString("data");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code +"|");
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if(StrUtil.equals(String.valueOf(code),"0")){
            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);
        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String phoneMd5 = jsonObject.getString("userPhone");

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(phoneMd5));
        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",1000);
        jsonObject.put("message","接受成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


}
